package com.hz.friends.fragment.nearby;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.androidquery.AQuery;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVGeoPoint;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVUser;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.hz.friends.activity.MaintabsActivity;
import com.hz.friends.activity.R;
import com.hz.friends.application.CustomApplication;
import com.hz.friends.chat.GroupChatActivity;
import com.hz.friends.group.CreateGroupActivity;
import com.hz.friends.serverrequest.ALCCPEngine;
import com.hz.friends.serverrequest.ALCCPEngine.ALGroupType;
import com.hz.friends.serverrequest.ALUserEngine;
import com.hz.friends.serverrequest.ALEngineConfig.CallBack;
import com.hz.friends.utils.MLog;

public class HotRoomListView extends BaseNearbyListView {
	private Context mcontext;
	private PullToRefreshListView mlistview;
	private final int limit = 1000;// 分页
	private int skip = 0;// 跳过记录条数
	private String TAG = this.getClass().getSimpleName();
	private HotRoomAdpter madpter;
	private AQuery aq;
	private TextView txv_nodata;
	private View view;

	public HotRoomListView(Context context) {
		this.mcontext = context;
		view = LayoutInflater.from(context).inflate(R.layout.nearby_item, null);
		mlistview = (PullToRefreshListView) view.findViewById(R.id.mlistview);
		txv_nodata = (TextView) view.findViewById(R.id.txv_nodata);
		init();
		initEvents();
		uploadHotRoomlist();
	}

	public View getView() {
		return view;
	}

	public void getData() {
		madpter.clearData();
		madpter.notifyDataSetChanged();
		uploadHotRoomlist();
	}

	private void init() {
		aq = new AQuery(this.mcontext);
		int diverheight = (int) TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_DIP, 10, mcontext.getResources()
						.getDisplayMetrics());
		mlistview.getRefreshableView().setDivider(
				mcontext.getResources()
						.getDrawable(android.R.color.transparent));
		mlistview.getRefreshableView().setDividerHeight(diverheight);
		// mlistview.getRefreshableView().setFooterDividersEnabled(false);
		// mlistview.getRefreshableView().setHeaderDividersEnabled(false);
		madpter = new HotRoomAdpter();
		mlistview.setAdapter(madpter);
	}

	private void initEvents() {
		mlistview.setOnRefreshListener(new OnRefreshListener2<ListView>() {

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ListView> refreshView) {

			}

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				// onRefresh();
				txv_nodata.setVisibility(View.GONE);
				madpter.clearData();
				madpter.notifyDataSetChanged();
				uploadHotRoomlist();
			}
		});
		mlistview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				CustomApplication.getInstance().currgroup = madpter
						.getItem(position - 1);
				Intent intent = new Intent(mcontext, GroupChatActivity.class);
				intent.putExtra("titlename", madpter.getItem(position - 1)
						.getString("name"));
				intent.putExtra("isGroup", true);
				mcontext.startActivity(intent);

			}
		});
	}

	// private void onRefresh() {
	// madpter.clearData();
	// skip = 0;
	// uploadFriends1();
	//
	// }

	// 热门聊天室
	private void uploadHotRoomlist() {
		// ALCCPEngine.defauleEngine().getGroupListWithNear(39.90248f,
		// 116.2381f,
		ALCCPEngine.defauleEngine().getGroupListOfHot(grouptype, limit,
				new ArrayList<AVObject>(), new CallBack() {

					@Override
					public void done(Object object, AVException avexception) {
						MLog.i(TAG, "uploadHotRoomlist avexception:"
								+ avexception + "  object:" + object);
						mlistview.onRefreshComplete();
						txv_nodata.setVisibility(View.GONE);
						if (avexception == null) {
							List<AVObject> data = (List<AVObject>) object;
							if (data == null || data.size() == 0) {
								if (madpter.getCount() == 0) {
									// ((MaintabsActivity) mcontext)
									// .showSysToast("没有好友");
									txv_nodata.setVisibility(View.VISIBLE);
								} else {
									CustomApplication.getInstance().showToast(
											"没有更多");
								}
							} else {
								skip = skip + data.size();
								madpter.addData(data);
								madpter.notifyDataSetChanged();
							}
						} else {
							avexception.printStackTrace();
							CustomApplication.getInstance().showToast(
									"搜索附近聊天室错误");
						}

					}
				});

	}

	public class HotRoomAdpter extends BaseAdapter {
		private List<AVObject> listdata = new ArrayList<AVObject>();

		@Override
		public int getCount() {
			return listdata.size();
		}

		public void addData(List<AVObject> listdata) {
			if (listdata == null)
				return;
			this.listdata.addAll(listdata);

		}

		@Override
		public AVObject getItem(int position) {
			return this.listdata.get(position);
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		public void clearData() {
			this.listdata.clear();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = LayoutInflater.from(mcontext).inflate(
					R.layout.adpter_hotroom, null);
			TextView txv_chatroom_name = (TextView) view
					.findViewById(R.id.txv_chatroom_name); // 聊天室名称
			TextView txv_chatroom_km = (TextView) view
					.findViewById(R.id.txv_chatroom_km); // 聊天室距离
			TextView txv_chatroom_peoplenum = (TextView) view
					.findViewById(R.id.txv_chatroom_peoplenum);// 聊天室人数
			TextView txv_chatroom_msgnum = (TextView) view
					.findViewById(R.id.txv_chatroom_msgnum);// 聊天室消息数
			TextView txv_chatroom_chatroomtype = (TextView) view
					.findViewById(R.id.txv_chatroom_chatroomtype);// 聊天室类型
			ImageView imv_roompic = (ImageView) view
					.findViewById(R.id.imv_roompic);// 聊天室背景图
			LinearLayout layout_tips = (LinearLayout) view
					.findViewById(R.id.layout_tips);// 没有图片时提示

			AVObject itemobj = listdata.get(position);
			String name = itemobj.getString("name");
			String picUrl = itemobj.getString("coverURL");
			int peoplenum = itemobj.getInt("numberOfMember");
			int roomtype = itemobj.getInt("type");
//			AVGeoPoint mgeopoint = new AVGeoPoint(39.90248f, 116.2381f);
			AVGeoPoint togeopoint = itemobj.getAVGeoPoint("location");
		 

			txv_chatroom_name.setText(name);
			if (peoplenum <= 0) {
				txv_chatroom_peoplenum.setText(String.valueOf(0));
			} else {
				txv_chatroom_peoplenum.setText(String.valueOf(peoplenum));
			}
			txv_chatroom_msgnum.setText(String.valueOf(0));
			if (roomtype == ALGroupType.ALGroupTypeOfBusiness.get_value()) {
				txv_chatroom_chatroomtype.setText("Business");
			} else if (roomtype == ALGroupType.ALGroupTypeOfFood.get_value()) {
				txv_chatroom_chatroomtype.setText("Food");
			} else if (roomtype == ALGroupType.ALGroupTypeOfNews.get_value()) {
				txv_chatroom_chatroomtype.setText("News");
			} else if (roomtype == ALGroupType.ALGroupTypeOfChat.get_value()) {
				txv_chatroom_chatroomtype.setText("Chat");
			} else if (roomtype == ALGroupType.ALGroupTypeOfEntertainMent
					.get_value()) {
				txv_chatroom_chatroomtype.setText("Entertainment");
			}
			setDistance(togeopoint, txv_chatroom_km);

			aq.id(imv_roompic).image(picUrl, true, true);
			if (TextUtils.isEmpty(picUrl))
				layout_tips.setVisibility(View.VISIBLE);
			else
				layout_tips.setVisibility(View.GONE);

			return view;
		}

		private void setDistance(AVGeoPoint togeopoint,TextView txv) {
			AVGeoPoint mgeopoint = AVUser.getCurrentUser().getAVGeoPoint("location");
			if(mgeopoint == null || togeopoint == null){
				txv.setText("unknow");
				return;
			}
			double distan = mgeopoint.distanceInKilometersTo(togeopoint);
			  DecimalFormat  df = new DecimalFormat("#.##");
				double km = distan/1000;
			   txv.setText(df.format(km)+" km");
			
		}
		

		// private void setDistance(int mi, TextView txv) {
		// if (mi < 101) {
		// txv.setText("100米以内");
		// } else if (mi < 1001) {
		// txv.setText(mi + "米");
		// } else {
		// int km = mi / 1000;
		// int xiaoshu = mi % 1000 / 100;
		// if (xiaoshu > 0) {
		// txv.setText(km + "." + xiaoshu + "公里");
		// } else {
		// txv.setText(km + "公里");
		// }
		// }
		// }
	}

}
